<template>
	<ui-form
		v-if="schemas && schemas.length"
		ref="form"
	>
		<ui-form-group
			:label="title"
		>
			<ui-form-item
				v-for="item in schemas"
				:key="item.id"
				:label="item.name"
				:show-arrow="item.type === 7"
			>
				<dynamic-form-control
					:value="innerValue[item.id]"
					:schema="item"
					@input="handleControlValueChange(item, $event)"
				></dynamic-form-control>
			</ui-form-item>
		</ui-form-group>
	</ui-form>
</template>

<script>
	import DynamicFormControl from './dynamic-form-control/dynamic-form-control.vue'
	
	export default {
		name: 'BiDynamicForm',
		components: {
			DynamicFormControl
		},
		props: {
			title: {
				type: String
			},
			value: {
				type: Object
			},
			schemas: {
				type: Array
			}
		},
		computed: {
			innerValue: {
				get () {
					return this.value || {}
				},
				set (val) {
					this.$emit('input', val)
				}
			}
		},
		methods: {
			handleControlValueChange (item, value) {
				if (item.id) {
					this.innerValue = Object.assign({
						[item.id]: value
					}, this.innerValue)
					this.$emit('change', {
						field: item.id,
						value
					})
				}
			},
			validate () {
				return this.$refs.form.validate()
			}
		}
	}
</script>

<style>
</style>
